/****************************************************************************
 **
 ** Copyright (C) 2004-2008 Trolltech ASA. All rights reserved.
 **
 ** This file is part of the documentation of the Qt Toolkit.
 **
 ** This file may be used under the terms of the GNU General Public
 ** License versions 2.0 or 3.0 as published by the Free Software
 ** Foundation and appearing in the files LICENSE.GPL2 and LICENSE.GPL3
 ** included in the packaging of this file.  Alternatively you may (at
 ** your option) use any later version of the GNU General Public
 ** License if such license has been publicly approved by Trolltech ASA
 ** (or its successors, if any) and the KDE Free Qt Foundation. In
 ** addition, as a special exception, Trolltech gives you certain
 ** additional rights. These rights are described in the Trolltech GPL
 ** Exception version 1.2, which can be found at
 ** http://www.trolltech.com/products/qt/gplexception/ and in the file
 ** GPL_EXCEPTION.txt in this package.
 **
 ** Please review the following information to ensure GNU General
 ** Public Licensing requirements will be met:
 ** http://trolltech.com/products/qt/licenses/licensing/opensource/. If
 ** you are unsure which license is appropriate for your use, please
 ** review the following information:
 ** http://trolltech.com/products/qt/licenses/licensing/licensingoverview
 ** or contact the sales department at sales@trolltech.com.
 **
 ** In addition, as a special exception, Trolltech, as the sole
 ** copyright holder for Qt Designer, grants users of the Qt/Eclipse
 ** Integration plug-in the right for the Qt/Eclipse Integration to
 ** link to functionality provided by Qt Designer and its related
 ** libraries.
 **
 ** This file is provided "AS IS" with NO WARRANTY OF ANY KIND,
 ** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR
 ** A PARTICULAR PURPOSE. Trolltech reserves all rights not expressly
 ** granted herein.
 **
 ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
 ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 **
 ****************************************************************************/

/* This file originally comes from Qt Tetrix example code.  I don't claim this
 * as my own work.  I mearly modified it to meet the project specifications */

#include <QtGui>
#include <cassert>
#include <iostream>

#include "tetrixboard.h"
#include "piecegenerator.h"
#include "keyconfig.h"

int TetrixBoard::timeoutTime = 500;

TetrixBoard::TetrixBoard(const char *pieceFileName, QWidget *parent)
    : QFrame(parent)
{
    setFrameStyle(QFrame::Panel | QFrame::Sunken);
    setFocusPolicy(Qt::StrongFocus);
    isStarted = false;
    isPaused = false;
    isGameOver = false;
    clearBoard();
    curPiece.setShape (0, 0);

    if (pieceFileName == 0)
        pieceGen = new RandomPieceGenerator;
    else
        pieceGen = new FilePieceGenerator(pieceFileName);

    assert(pieceGen);

    int nBlocks;
    const int *shape = pieceGen->getNextPiece(nBlocks);;
    nextPiece.setShape(shape, nBlocks);
}

void TetrixBoard::setNextPieceLabel(QLabel *label)
{
    nextPieceLabel = label;
}

QSize TetrixBoard::sizeHint() const
{
    return QSize(BoardWidth * 15 + frameWidth() * 2,
                 BoardHeight * 15 + frameWidth() * 2);
}

QSize TetrixBoard::minimumSizeHint() const
{
    return QSize(BoardWidth * 5 + frameWidth() * 2,
                 BoardHeight * 5 + frameWidth() * 2);
}

void TetrixBoard::setKey(TetrixBoard::Keys key, KeyConfig::KeyCode value)
{
    if (key < Numkeys && value < KeyConfig::NumKeycodes)
        keys[key] = value;
}

void TetrixBoard::start()
{
    if (isPaused)
        return;

    isStarted = true;
    isGameOver = false;
    isWaitingAfterLine = false;
    numLinesRemoved = 0;
    totalPieces = 0;
    totalBlocks = 0;
    piece4Blocks = 0;
    piece5Blocks = 0;
    piece6Blocks = 0;
    piece7Blocks = 0;
    clearBoard();

    emit linesRemovedChanged(numLinesRemoved);
    emit totalPiecesChanged(totalPieces);
    emit totalBlocksChanged(totalBlocks);
    emit piece4BlocksChanged(piece4Blocks);
    emit piece5BlocksChanged(piece5Blocks);
    emit piece6BlocksChanged(piece6Blocks);
    emit piece7BlocksChanged(piece7Blocks);

    newPiece();
    timer.start(timeoutTime, this);
}

void TetrixBoard::pause()
{
    if (!isStarted)
        return;

    isPaused = !isPaused;
    if (isPaused) {
        timer.stop();
    } else {
        timer.start(timeoutTime, this);
    }
    update();
}

void TetrixBoard::paintEvent(QPaintEvent *event)
{
    QFrame::paintEvent(event);

    QPainter painter(this);
    QRect rect = contentsRect();

    if (isPaused) {
        painter.drawText(rect, Qt::AlignCenter, tr("Pause"));
        return;
    }

    if (isGameOver) {
        painter.drawText(rect, Qt::AlignCenter, tr("Game Over"));
        return;
    }

    int boardTop = rect.bottom() - BoardHeight*squareHeight();

    for (int i = 0; i < BoardHeight; ++i) {
        for (int j = 0; j < BoardWidth; ++j) {
            int numBlocks = shapeAt(j, BoardHeight - i - 1);
            if (numBlocks != 0)
                drawSquare(painter, rect.left() + j * squareWidth(),
                           boardTop + i * squareHeight(), numBlocks);
        }
    }

    if (curPiece.numBlocks() != 0) {
        for (int i = 0; i < curPiece.numBlocks (); ++i) {
            int x = curX + curPiece.x(i);
            int y = curY - curPiece.y(i);
            drawSquare(painter, rect.left() + x * squareWidth(),
                       boardTop + (BoardHeight - y - 1) * squareHeight(),
                       curPiece.numBlocks());
        }
    }
}

void TetrixBoard::keyPressEvent(QKeyEvent *event)
{
    if (!isStarted || isPaused || isGameOver || curPiece.numBlocks() == 0) {
        QFrame::keyPressEvent(event);
        return;
    }

    /*
    switch (event->key()) {
    case Qt::Key_Left:
        tryMove(curPiece, curX - 1, curY);
        break;
    case Qt::Key_Right:
        tryMove(curPiece, curX + 1, curY);
        break;
    case Qt::Key_Down:
        tryMove(curPiece.rotatedRight(), curX, curY);
        break;
    case Qt::Key_Up:
        tryMove(curPiece.rotatedLeft(), curX, curY);
        break;
    case Qt::Key_Space:
        dropDown();
        break;
    case Qt::Key_D:
        oneLineDown();
        break;
    default:
        QFrame::keyPressEvent(event);
    }
    */

    if (event->key() == KeyConfig::qtKeyMap[keys[RotateKey]].qtKeycode)
        tryMove(curPiece.rotatedRight(), curX, curY);
    else if (event->key() == KeyConfig::qtKeyMap[keys[LeftKey]].qtKeycode)
        tryMove(curPiece, curX - 1, curY);
    else if (event->key() == KeyConfig::qtKeyMap[keys[RightKey]].qtKeycode)
        tryMove(curPiece, curX + 1, curY);
    else if (event->key() == KeyConfig::qtKeyMap[keys[FallKey]].qtKeycode)
        oneLineDown();
}

void TetrixBoard::timerEvent(QTimerEvent *event)
{
    if (event->timerId() == timer.timerId()) {
        if (isWaitingAfterLine) {
            isWaitingAfterLine = false;
            newPiece();
            timer.start(timeoutTime, this);
        } else {
            oneLineDown();
        }
    } else {
        QFrame::timerEvent(event);
    }
}

void TetrixBoard::clearBoard()
{
    for (int i = 0; i < BoardHeight * BoardWidth; ++i)
        board[i] = 0;
}

void TetrixBoard::dropDown()
{
    int dropHeight = 0;
    int newY = curY;
    while (newY > 0) {
        if (!tryMove(curPiece, curX, newY - 1))
            break;
        --newY;
        ++dropHeight;
    }
    pieceDropped();
}

void TetrixBoard::oneLineDown()
{
    if (!tryMove(curPiece, curX, curY - 1))
        pieceDropped();
}

void TetrixBoard::pieceDropped()
{
    for (int i = 0; i < curPiece.numBlocks(); ++i) {
        int x = curX + curPiece.x(i);
        int y = curY - curPiece.y(i);
        shapeAt(x, y) = curPiece.numBlocks();
    }

    ++totalPieces;
    emit totalPiecesChanged(totalPieces);

    totalBlocks += curPiece.numBlocks();
    emit totalBlocksChanged(totalBlocks);

    switch (curPiece.numBlocks()) {
    case 4: ++piece4Blocks; emit piece4BlocksChanged(piece4Blocks); break;
    case 5: ++piece5Blocks; emit piece5BlocksChanged(piece5Blocks); break;
    case 6: ++piece6Blocks; emit piece6BlocksChanged(piece6Blocks); break;
    case 7: ++piece7Blocks; emit piece7BlocksChanged(piece7Blocks); break;
    }

    removeFullLines();

    if (!isWaitingAfterLine)
        newPiece();
}

void TetrixBoard::removeFullLines()
{
    int numFullLines = 0;

    for (int i = BoardHeight - 1; i >= 0; --i) {
        bool lineIsFull = true;

        for (int j = 0; j < BoardWidth; ++j) {
            if (shapeAt(j, i) == 0) {
                lineIsFull = false;
                break;
            }
        }

        if (lineIsFull) {
            ++numFullLines;
            for (int k = i; k < BoardHeight - 1; ++k) {
                for (int j = 0; j < BoardWidth; ++j)
                    shapeAt(j, k) = shapeAt(j, k + 1);
            }
            for (int j = 0; j < BoardWidth; ++j)
                shapeAt(j, BoardHeight - 1) = 0;
        }
    }

    if (numFullLines > 0) {
        numLinesRemoved += numFullLines;
        emit linesRemovedChanged(numLinesRemoved);

        timer.start(500, this);
        isWaitingAfterLine = true;
        curPiece.setShape(NULL, 0);
        update();
    }
}

void TetrixBoard::newPiece()
{
    if (nextPiece.numBlocks() == 0) {
        int nBlocks;
        const int *shape = pieceGen->getNextPiece(nBlocks);
        nextPiece.setShape(shape, nBlocks);
    }

    curPiece = nextPiece;
    int nBlocks;
    const int *shape = pieceGen->getNextPiece(nBlocks);
    nextPiece.setShape(shape, nBlocks);
    curX = (BoardWidth - curPiece.maxX()) / 2;
    curY = BoardHeight - 1 + curPiece.minY();

    if (!tryMove(curPiece, curX, curY)) {
        curPiece.setShape(NULL, 0);
        nextPiece.setShape(NULL, 0);
        timer.stop();
        isStarted = false;
        isGameOver = true;
        update();
    }

    showNextPiece();
}

void TetrixBoard::showNextPiece()
{
    if (!nextPieceLabel)
        return;

    int dx = nextPiece.maxX() - nextPiece.minX() + 1;
    int dy = nextPiece.maxY() - nextPiece.minY() + 1;

    QPixmap pixmap(dx * squareWidth(), dy * squareHeight());
    QPainter painter(&pixmap);
    painter.fillRect(pixmap.rect(), nextPieceLabel->palette().background());

    for (int i = 0; i < nextPiece.numBlocks(); ++i) {
        int x = nextPiece.x(i) - nextPiece.minX();
        int y = nextPiece.y(i) - nextPiece.minY();
        drawSquare(painter, x * squareWidth(), y * squareHeight(),
                   nextPiece.numBlocks());
    }
    nextPieceLabel->setPixmap(pixmap);
}

bool TetrixBoard::tryMove(const TetrixPiece &newPiece, int newX, int newY)
{
    for (int i = 0; i < newPiece.numBlocks(); ++i) {
        int x = newX + newPiece.x(i);
        int y = newY - newPiece.y(i);
        if (x < 0 || x >= BoardWidth || y < 0 || y >= BoardHeight)
            return false;
        if (shapeAt(x, y) != 0)
            return false;
    }

    curPiece = newPiece;
    curX = newX;
    curY = newY;
    update();
    return true;
}

void TetrixBoard::drawSquare(QPainter &painter, int x, int y, int numBlocks)
{
    static const QRgb colorTable[5] = {
        0x000000, 0xCC6666, 0x66CC66, 0x6666CC, 0xCCCC66
    };

    QColor color = colorTable[numBlocks - 3];
    painter.fillRect(x + 1, y + 1, squareWidth() - 2, squareHeight() - 2,
                     color);
 
    painter.setPen(color.light());
    painter.drawLine(x, y + squareHeight() - 1, x, y);
    painter.drawLine(x, y, x + squareWidth() - 1, y);
 
    painter.setPen(color.dark());
    painter.drawLine(x + 1, y + squareHeight() - 1,
                     x + squareWidth() - 1, y + squareHeight() - 1);
    painter.drawLine(x + squareWidth() - 1, y + squareHeight() - 1,
                     x + squareWidth() - 1, y + 1);
}
